//
//  RetrievePasswordViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/3/9.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import DynamicBlurView
import Alamofire
import PKHUD
import PKHUD
import YYModel
import SwiftyJSON

class RetrievePasswordViewController: BaseViewController {
    @IBOutlet weak var bgImageView: UIImageView!
    @IBOutlet weak var phoneTextField: UITextField!
    @IBOutlet weak var vcTextField: UITextField!
    @IBOutlet var borderViews: [UIView]!
    @IBOutlet weak var codeButton: UIButton!
    
    var timer: Timer?
    var sendCount: Int = 60
    
    override func viewDidLoad() {
        super.viewDidLoad()
       setUI()
        // Do any additional setup after loading the view.
    }
    
    func setUI() {
        titleLabel(text: "找回密码", nil)
        let _ = borderViews.map({
            $0.layer.borderColor = UIColor.white.cgColor
            $0.layer.borderWidth = 1
        })
        
        phoneTextField.attributedPlaceholder = NSAttributedString(string: "请输入手机号", attributes: [NSAttributedStringKey.foregroundColor : UIColor(hex: 0xB6B6B6)])
        vcTextField.attributedPlaceholder = NSAttributedString(string: "请输入验证码", attributes: [NSAttributedStringKey.foregroundColor : UIColor(hex: 0xB6B6B6)])
        
        let blurView = DynamicBlurView(frame: bgImageView.bounds)
        blurView.blurRadius = 10
        view.insertSubview(blurView, aboveSubview: bgImageView)
    }
    
    override func setNavigation() {
        
    }
   
    @IBAction func getCodeAction(_ sender: Any) {
        if (phoneTextField.text?.isEmpty)! {
            self.showToast(msg:"手机号码不能为空")
            return
        }
        if !(self.isValidPhone(phone: phoneTextField.text! as NSString)) {
            self.showToast(msg:"手机号码格式不对")
            return
        }
        let requesturl = "\(BaseURL)\(getCodeUrl)"
        let parameter:[String : Any] = ["mp":phoneTextField.text!, "type": "2"]
        
        self.codeButton.isUserInteractionEnabled = false
        
        Alamofire.request(requesturl, method: .post, parameters: parameter, encoding: URLEncoding.default, headers: nil).responseJSON { [weak self](response) in
            
            let result = response.result.value as? NSDictionary
            let json = JSON(result!)
            if(response.error == nil){
                
                self?.sendCount = 60
                self?.timer = Timer.scheduledTimer(timeInterval: 1, target: self!, selector: #selector(self?.updateCode), userInfo: nil, repeats: true)
                self?.showToast(msg:json["message"].string!)
                
            }else{
                self?.codeButton.isUserInteractionEnabled = true
                self?.showToast(msg:json["message"].string!)
                print("请求失败\(String(describing: response.error))")
            }
            
        }
    }
    
    
    
    @objc func updateCode() -> Void {
        var enable: Bool = false
        var title: String?
        if self.sendCount > 0 {
            title = "重新发送\(self.sendCount)"
            enable = false
        }else{
            title = "发送验证码"
            enable = true
            if self.timer != nil && (self.timer?.isValid)! {
                self.timer?.invalidate()
            }
            self.timer = nil
            self.sendCount = 60
        }
        
        self.codeButton.titleLabel?.text = title
        self.codeButton.setTitle(title, for: .normal)
        self.codeButton.isUserInteractionEnabled = enable
        self.sendCount -= 1
    }
    
    @IBAction func nextTap(_ sender: UIButton) {
        if (phoneTextField.text?.isEmpty)! {
            self.showToast(msg:"请输入手机号码")
            return
        }
        if !(self.isValidPhone(phone: phoneTextField.text! as NSString)) {
            self.showToast(msg:"手机号码格式不对")
            return
        }
        if (self.vcTextField.text?.isEmpty)! {
            self.showToast(msg:"请输入验证码")
            return
        }

        let requesturl = "\(BaseURL)\(verifyCodeUrl)"
        let parameter:[String : Any] = ["mp":self.phoneTextField.text!,"vcode":self.vcTextField.text!]
        Alamofire.request(requesturl, method: .post, parameters: parameter, encoding: URLEncoding.default, headers: nil).responseJSON { [weak self](response) in
            
            let result = response.result.value as? NSDictionary
            let json = JSON(result!)
            if(response.error == nil){
                if json["code"].int == 1 {
                    let resetPasswordVC = ResetPasswordViewController(nibName: "\(ResetPasswordViewController.self)", bundle: nil)
                    resetPasswordVC.phone = self?.phoneTextField.text
                    resetPasswordVC.vcode = self?.vcTextField.text
                    self?.navigationController?.pushViewController(resetPasswordVC, animated: true)
                }else {
                    self?.showToast(msg:json["message"].string!)
                }
            }else{
                self?.showToast(msg:json["message"].string!)
                print("请求失败\(String(describing: response.error))")
            }
            
        }
    }
}
